#!/bin/bash
# 使用ps命令监控某个进程的内存占用, 如果超过阈值则记录日志并退出
# ps用法：ps -p PID -o rss,vsz,pid,ppid,%mem,%cpu,cmd --sort=-%mem
# 用法： ./ps_mem_monitor.sh PID

i=0
countdown=300
LOGFILE=~/celery_memory_increase.log
PID=$1
THRESHOLD_MEM=4.0

function got_ps_memory_percent() {
  if [ -z "$PID" ]; then
    echo  "$(ps -e -o pid,%mem,cmd|grep celery | grep -v grep | awk '{print $2}')"
  else
    echo "$(ps -p $PID -o %mem | tail -1)"
  fi
}


while true
do
    mem_percents=$(got_ps_memory_percent)
    for mem_percent in $mem_percents
    do
        echo "mem_percent: $mem_percent"
        # 浮点数比较
        if (( $(echo "$mem_percent > $THRESHOLD_MEM" | bc -l) )); then
            dt=$(date +"%Y-%m-%d %H:%M:%S")
            echo "$dt memory usage:$mem_percent" >> $LOGFILE
            ((i++))
            if [[ $i -gt $countdown ]]; then
                exit 0
            fi
        fi
    done
    sleep 1
done
